/**
 * 栈的链表实现
*/
#include <stdlib.h>

#ifndef STACK_ARRAY
#define STACK_ARRAY

#ifndef StackElementType
#define StackElementType int
#endif

typedef struct StackNode StackNode;
struct StackNode {
    StackElementType data;
    StackNode* next;
};

typedef struct Stack Stack;
struct Stack {
    StackNode* top;
    int size;
    int capacity;
};

Stack* createStack(int capacity) {
    Stack* s = calloc(1, sizeof(Stack));
    StackNode* node = calloc(1, sizeof(StackNode));
    node->next = NULL;
    s->top = node;
    s->size = 0;
    s->capacity = capacity;
    return s;
}

void freeStack(Stack* stack) {
    for (StackNode* node=stack->top; node != NULL; ) {
        StackNode* sn = node;
        node = sn->next;
        free(sn);
    }
    free(stack);
}

int isStackEmpty(Stack* s) {
    return s->top->next == NULL;
}

int isStackFull(Stack* s) {
    return s->size >= s->capacity;
}

StackElementType peekFirst(Stack* s) {
    return s->top->next->data;
}

int pushStack(Stack* s, StackElementType value) {
    StackNode* node = calloc(1, sizeof(StackNode));
    node->data = value;
    node->next = s->top->next;
    s->top->next = node;
    s->size++;
    return 1;
}

StackElementType popStack(Stack* s) {
    StackNode* node = s->top->next;
    StackElementType e = node->data;
    s->top->next = node->next;
    s->size--;
    free(node);
    return e;
}

#endif 
